<?php


/**
 * 取得拍卖活动信息
 * @param   int     $act_id     活动id
 * @return  array
 */
function auction_info($act_id, $config = false){
	
	$CommonModel				=	new CommonModel();
	
    $sql				 		= 	"SELECT * FROM " . 'ybr_goods_activity' . " WHERE act_id = '$act_id'";
    $auction 					= 	$CommonModel->getRow($sql);
    if ($auction['act_type'] != GAT_AUCTION){
        return array();
    }
    $auction['status_no'] = auction_status($auction);
    if ($config == true){
        $auction['start_time'] 	= 	local_date('Y-m-d H:i', $auction['start_time']);
        $auction['end_time'] 	= 	local_date('Y-m-d H:i', $auction['end_time']);
    }
    else{
        $auction['start_time'] 	= 	local_date($GLOBALS['_CFG']['time_format'], $auction['start_time']);
        $auction['end_time'] 	= 	local_date($GLOBALS['_CFG']['time_format'], $auction['end_time']);
    }
    $ext_info 					= 	unserialize($auction['ext_info']);
    $auction 					= 	array_merge($auction, $ext_info);
    $auction['formated_start_price'] 	= 	price_format($auction['start_price']);
    $auction['formated_end_price'] 		= 	price_format($auction['end_price']);
    $auction['formated_amplitude'] 		= 	price_format($auction['amplitude']);
    $auction['formated_deposit'] 		= 	price_format($auction['deposit']);

    /* 查询出价用户数和最后出价 */
    $sql 						= 	"SELECT COUNT(DISTINCT bid_user) FROM " . 'ybr_auction_log' .
            						" WHERE act_id = '$act_id'";
    
    $auction['bid_user_count'] 	= 	$CommonModel->getOne($sql);
    
    if ($auction['bid_user_count'] > 0){
        $sql 					= 	"SELECT a.*, u.user_name " .
					                "FROM " . 'ybr_auction_log' . " AS a, " .
					                'ybr_users' . " AS u " .
					                "WHERE a.bid_user = u.user_id " .
					                "AND act_id = '$act_id' " .
					                "ORDER BY a.log_id DESC";
        
        $row 					= 	$CommonModel->getRow($sql);
        $row['formated_bid_price'] 	= 	price_format($row['bid_price'], false);
        $row['bid_time'] 			= 	local_date($GLOBALS['_CFG']['time_format'], $row['bid_time']);
        $auction['last_bid'] 		= 	$row;
    }

    /* 查询已确认订单数 */
    if ($auction['status_no'] > 1){
        $sql 					= 	"SELECT COUNT(*)" .
					                " FROM " . 'ybr_order_info' .
					                " WHERE extension_code = 'auction'" .
					                " AND extension_id = '$act_id'" .
					                " AND order_status " . db_create_in(array(OS_CONFIRMED, OS_UNCONFIRMED));
        $auction['order_count'] = 	$CommonModel->getOne($sql);
    }
    else{
        $auction['order_count'] = 0;
    }

    /* 当前价 */
    $auction['current_price'] 			= 	isset($auction['last_bid']) ? $auction['last_bid']['bid_price'] : $auction['start_price'];
    $auction['formated_current_price'] 	= 	price_format($auction['current_price'], false);

    return $auction;
}

/**
 * 计算拍卖活动状态（注意参数一定是原始信息）
 * @param   array   $auction    拍卖活动原始信息
 * @return  int
 */
function auction_status($auction){
    $now 			= 	gmtime();
    if ($auction['is_finished'] == 0){
        if ($now < $auction['start_time']){
            return PRE_START; // 未开始
        }
        elseif ($now > $auction['end_time']){
            return FINISHED; // 已结束，未处理
        }
        else{
            return UNDER_WAY; // 进行中
        }
    }
    elseif ($auction['is_finished'] == 1){
        return FINISHED; // 已结束，未处理
    }
    else{
        return SETTLED; // 已结束，已处理
    }
}


/**
 * 获得指定商品的关联商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_linked_goods($goods_id){	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	'SELECT g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' .
                		"IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
	                	'g.market_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
	            		'FROM ' . 'ybr_link_goods' . ' lg ' .
	            		'LEFT JOIN ' . 'ybr_goods' . ' AS g ON g.goods_id = lg.link_goods_id ' .
	            		"LEFT JOIN " . 'ybr_member_price' . " AS mp ".
	                    "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
	            		"WHERE lg.goods_id = '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
	            		"LIMIT " . $GLOBALS['_CFG']['related_goods_number'];
    $res 			= 	$CommonModel->query($sql);

    $arr 			= 	array();
    
    foreach($res as $row){
    	$arr[$row['goods_id']]['goods_id']     	= 	$row['goods_id'];
        $arr[$row['goods_id']]['goods_name']   	= 	$row['goods_name'];
        $arr[$row['goods_id']]['short_name']   	= 	$GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        //$arr[$row['goods_id']]['goods_thumb']  	= 	get_image_path($row['goods_id'], $row['goods_thumb'], true);
        //$arr[$row['goods_id']]['goods_img']    	= 	get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['market_price']	= 	price_format($row['market_price']);
        $arr[$row['goods_id']]['shop_price']   	= 	price_format($row['shop_price']);
        //$arr[$row['goods_id']]['url']          	= 	build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0){
            $arr[$row['goods_id']]['promote_price'] 			= 	bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$row['goods_id']]['formated_promote_price'] 	= 	price_format($arr[$row['goods_id']]['promote_price']);
        }
        else{
            $arr[$row['goods_id']]['promote_price'] = 0;
        }
    }
    return $arr;
}


/**
 * 获得商品的属性和规格
 *
 * @access  public
 * @param   integer $goods_id
 * @return  array
 */
function get_goods_properties($goods_id){
	
	$CommonModel	=	new CommonModel();
	
    /* 对属性进行重新排序和分组 */
    $sql 			= 	"SELECT attr_group ".
	            		"FROM " . 'ybr_goods_type' . " AS gt, " . 'ybr_goods' . " AS g ".
	            		"WHERE g.goods_id='$goods_id' AND gt.cat_id=g.goods_type";
    $grp 			= 	$CommonModel->getOne($sql);

    if (!empty($grp)){
        $groups 	= 	explode("\n", strtr($grp, "\r", ''));
    }

    /* 获得商品的规格 */
    $sql 			= 	"SELECT a.attr_id, a.attr_name, a.attr_group, a.is_linked, a.attr_type, ".
                		"g.goods_attr_id, g.attr_value, g.attr_price " .
			            'FROM ' . 'ybr_goods_attr' . ' AS g ' .
			            'LEFT JOIN ' . 'ybr_attribute' . ' AS a ON a.attr_id = g.attr_id ' .
			            "WHERE g.goods_id = '$goods_id' " .
			            'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
    $res 			= 	$CommonModel->query($sql);

    $arr['pro'] 	= 	array();     // 属性
    $arr['spe'] 	= 	array();     // 规格
    $arr['lnk'] 	= 	array();     // 关联的属性

    foreach ($res AS $row){
        $row['attr_value'] 		= 	str_replace("\n", '<br />', $row['attr_value']);

        if ($row['attr_type'] == 0){
            $group 				= 	(isset($groups[$row['attr_group']])) ? $groups[$row['attr_group']] : $GLOBALS['_LANG']['goods_attr'];

            $arr['pro'][$group][$row['attr_id']]['name']  	= 	$row['attr_name'];
            $arr['pro'][$group][$row['attr_id']]['value'] 	= 	$row['attr_value'];
            $arr['pro'][$group][$row['attr_id']]['attr_id'] = 	$row['attr_id'];
        }
        else{
            $arr['spe'][$row['attr_id']]['attr_type'] 		= 	$row['attr_type'];
            $arr['spe'][$row['attr_id']]['name']     		= 	$row['attr_name'];
            $arr['spe'][$row['attr_id']]['attr_id']     	= 	$row['attr_id'];
            $arr['spe'][$row['attr_id']]['values'][] 		= 	array(
		                                                    	    'label'        => $row['attr_value'],
		                                                        	'price'        => $row['attr_price'],
		                                                        	'format_price' => price_format(abs($row['attr_price']), false),
		                                                        	'id'           => $row['goods_attr_id']
        	    												);
        }

        if ($row['is_linked'] == 1){
            /* 如果该属性需要关联，先保存下来 */
            $arr['lnk'][$row['attr_id']]['name']  		= 	$row['attr_name'];
            $arr['lnk'][$row['attr_id']]['value'] 		= 	$row['attr_value'];
            $arr['lnk'][$row['attr_id']]['attr_id'] 	= 	$row['attr_id'];
        }
    }
    return $arr;
}


/**
 * 取得跟商品关联的礼包列表
 *
 * @param   string  $goods_id    商品编号
 *
 * @return  礼包列表
 */
function get_package_goods_list($goods_id){
	
	$CommonModel		=	new CommonModel();
	
    $now 				= 	gmtime();
    $sql 				= 	"SELECT pg.goods_id, ga.act_id, ga.act_name, ga.act_desc, ga.goods_name, ga.start_time,
                   			ga.end_time, ga.is_finished, ga.ext_info
				            FROM " . 'ybr_goods_activity' . " AS ga, " . 'ybr_package_goods' . " AS pg
				            WHERE pg.package_id = ga.act_id
				            AND ga.start_time <= '" . $now . "'
				            AND ga.end_time >= '" . $now . "'
				            AND pg.goods_id = " . $goods_id . "
				            GROUP BY ga.act_id
				            ORDER BY ga.act_id ";
    $res 				= 	$CommonModel->query($sql);

    foreach ($res as $tempkey => $value){
        $subtotal 		= 	0;
        $row 			= 	unserialize($value['ext_info']);
        unset($value['ext_info']);
        if ($row){
            foreach ($row as $key=>$val){
                $res[$tempkey][$key] = $val;
            }
        }

        $sql 			= 	"SELECT pg.package_id, pg.goods_id, pg.goods_number, pg.admin_id, p.goods_attr, g.goods_sn, g.goods_name, g.market_price, g.goods_thumb, IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price
                			FROM " . 'ybr_package_goods' . " AS pg
                    		LEFT JOIN ". 'ybr_goods' . " AS g
                        	ON g.goods_id = pg.goods_id
                    		LEFT JOIN ". 'ybr_products' . " AS p
                        	ON p.product_id = pg.product_id
                    		LEFT JOIN " . 'ybr_member_price' . " AS mp
                        	ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]'
                			WHERE pg.package_id = " . $value['act_id']. "
                			ORDER BY pg.package_id, pg.goods_id";

        $goods_res 		= 	$CommonModel->query($sql);

        foreach($goods_res as $key => $val){
            $goods_id_array[] 					= 	$val['goods_id'];
            //$goods_res[$key]['goods_thumb']  	= 	get_image_path($val['goods_id'], $val['goods_thumb'], true);
            $goods_res[$key]['market_price'] 	= 	price_format($val['market_price']);
            $goods_res[$key]['rank_price']   	= 	price_format($val['rank_price']);
            $subtotal 							+= 	$val['rank_price'] * $val['goods_number'];
        }

        /* 取商品属性 */
        $sql 			= 	"SELECT ga.goods_attr_id, ga.attr_value
                			FROM " .'ybr_goods_attr'. " AS ga, " .'ybr_attribute'. " AS a
			                WHERE a.attr_id = ga.attr_id
			                AND a.attr_type = 1
			                AND " . db_create_in($goods_id_array, 'goods_id');
        $result_goods_attr 	= 	$CommonModel->query($sql);

        $_goods_attr 		= 	array();
        foreach ($result_goods_attr as $value){
            $_goods_attr[$value['goods_attr_id']] 	= 	$value['attr_value'];
        }

        /* 处理货品 */
        $format 					= 	'[%s]';
        foreach($goods_res as $key => $val){
            if ($val['goods_attr'] != ''){
                $goods_attr_array 	= 	explode('|', $val['goods_attr']);

                $goods_attr 		= 	array();
                foreach ($goods_attr_array as $_attr){
                    $goods_attr[] 	= 	$_goods_attr[$_attr];
                }

                $goods_res[$key]['goods_attr_str'] 	= 	sprintf($format, implode('，', $goods_attr));
            }
        }

        $res[$tempkey]['goods_list']    = $goods_res;
        $res[$tempkey]['subtotal']      = price_format($subtotal);
        $res[$tempkey]['saving']        = price_format(($subtotal - $res[$tempkey]['package_price']));
        $res[$tempkey]['package_price'] = price_format($res[$tempkey]['package_price']);
    }
    
    return $res;
}

/**
 * 获得指定商品的关联文章
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  void
 */
function get_linked_articles($goods_id){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	'SELECT a.article_id, a.title, a.file_url, a.open_type, a.add_time ' .
            			'FROM ' . 'ybr_goods_article' . ' AS g, ' .
                		'ybr_article' . ' AS a ' .
            			"WHERE g.article_id = a.article_id AND g.goods_id = '$goods_id' AND a.is_open = 1 " .
            			'ORDER BY a.add_time DESC';
    $res 			= 	$CommonModel->query($sql);

    $arr 			= 	array();
    
    foreach($res as $row){
    	//$row['url']         = 	$row['open_type'] != 1 ? build_uri('article', array('aid'=>$row['article_id']), $row['title']) : trim($row['file_url']);
        $row['add_time']    = 	local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);
        $row['short_title'] = 	$GLOBALS['_CFG']['article_title_length'] > 0 ? sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];
        $arr[] 				= 	$row;
    }
    return $arr;
}

/**
 * 获得购物车中商品的配件
 *
 * @access  public
 * @param   array     $goods_list
 * @return  array
 */
function get_goods_fittings($goods_list = array()){
    $temp_index 			= 	0;
    $arr        			= 	array();

    $sql 					= 	'SELECT gg.parent_id, ggg.goods_name AS parent_name, gg.goods_id, gg.goods_price, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price AS org_price, ' .
                				"IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price ".
            					'FROM ' . ' ybr_group_goods ' . ' AS gg ' .
            					'LEFT JOIN ' . ' ybr_goods ' . ' AS g ON g.goods_id = gg.goods_id ' .
            					"LEFT JOIN " . ' ybr_member_price ' . " AS mp ".
                    			"ON mp.goods_id = gg.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
					            "LEFT JOIN " . 'ybr_goods' . " AS ggg ON ggg.goods_id = gg.parent_id ".
					            "WHERE gg.parent_id " . db_create_in($goods_list) . " AND g.is_delete = 0 AND g.is_on_sale = 1 ".
					            "ORDER BY gg.parent_id, gg.goods_id";
	
    $res 					= 	M()->query($sql);

    foreach($res as $row){
    	$arr[$temp_index]['parent_id']         = $row['parent_id'];//配件的基本件ID
        $arr[$temp_index]['parent_name']       = $row['parent_name'];//配件的基本件的名称
        $arr[$temp_index]['parent_short_name'] = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['parent_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['parent_name'];//配件的基本件显示的名称
        $arr[$temp_index]['goods_id']          = $row['goods_id'];//配件的商品ID
        $arr[$temp_index]['goods_name']        = $row['goods_name'];//配件的名称
        $arr[$temp_index]['short_name']        = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];//配件显示的名称
        $arr[$temp_index]['fittings_price']    = price_format($row['goods_price']);//配件价格
        $arr[$temp_index]['shop_price']        = price_format($row['shop_price']);//配件原价格
        $arr[$temp_index]['goods_thumb']       = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$temp_index]['goods_img']         = get_image_path($row['goods_id'], $row['goods_img']);
        //$arr[$temp_index]['url']               = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $temp_index ++;
    }
    return $arr;
}


/**
 * 获得指定商品的各会员等级对应的价格
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_user_rank_prices($goods_id, $shop_price){
    $sql 				= 	"SELECT rank_id, IFNULL(mp.user_price, r.discount * $shop_price / 100) AS price, r.rank_name, r.discount " .
				            'FROM ' . 'ybr_user_rank' . ' AS r ' .
				            'LEFT JOIN ' . 'ybr_member_price' . " AS mp ".
				            "ON mp.goods_id = '$goods_id' AND mp.user_rank = r.rank_id " .
				            "WHERE r.show_price = 1 OR r.rank_id = '$_SESSION[user_rank]'";
    $res 				= 	M()->query($sql);

    $arr 				= 	array();
    
    foreach($res as $row){
    	 $arr[$row['rank_id']] = array(
                        'rank_name' => htmlspecialchars($row['rank_name']),
                        'price'     => price_format($row['price'])
    	);
    }
    
    return $arr;
}

/**
 * 获得指定商品的相册
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_goods_gallery($goods_id,$type = null){
	
	
	if(!empty($type)){			
	    $sql 	= 	'SELECT img_id, img_url, thumb_url, img_desc' .
					' FROM ' . 'ybr_goods_gallery' .
					" WHERE goods_id = '$goods_id'  and img_desc='{$type}'  LIMIT " . $GLOBALS['_CFG']['goods_gallery_number'];	
	}
	else{
		$sql 	= 	'SELECT img_id, img_url, thumb_url, img_desc' .
					' FROM ' . 'ybr_goods_gallery' .
					" WHERE goods_id = '$goods_id' LIMIT " . $GLOBALS['_CFG']['goods_gallery_number'];
	}
    $row 			= 	M()->query($sql);
    return $row;
}


/**
 * 获得购买过该商品的人还买过的商品
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  array
 */
function get_also_bought($goods_id){
    $sql 			= 	'SELECT COUNT(b.goods_id ) AS num, g.goods_id, g.goods_name, g.goods_thumb, g.goods_img, g.shop_price, g.promote_price, g.promote_start_date, g.promote_end_date ' .
			            'FROM ' . 'ybr_order_goods' . ' AS a ' .
			            'LEFT JOIN ' . 'ybr_order_goods' . ' AS b ON b.order_id = a.order_id ' .
			            'LEFT JOIN ' . 'ybr_goods' . ' AS g ON g.goods_id = b.goods_id ' .
			            "WHERE a.goods_id = '$goods_id' AND b.goods_id <> '$goods_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 " .
			            'GROUP BY b.goods_id ' .
			            'ORDER BY num DESC ' .
			            'LIMIT ' . $GLOBALS['_CFG']['bought_goods'];
    $res 			= 	M()->query($sql);

    $key 			= 	0;
    $arr 			= 	array();
    
    foreach($res as $row){
    	$arr[$key]['goods_id']    = $row['goods_id'];
        $arr[$key]['goods_name']  = $row['goods_name'];
        $arr[$key]['short_name']  = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $arr[$key]['goods_thumb'] = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$key]['goods_img']   = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$key]['shop_price']  = price_format($row['shop_price']);
        //$arr[$key]['url']         = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);

        if ($row['promote_price'] > 0){
            $arr[$key]['promote_price'] = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $arr[$key]['formated_promote_price'] = price_format($arr[$key]['promote_price']);
        }
        else{
            $arr[$key]['promote_price'] = 0;
        }
        $key++;
    }
    return $arr;
}



/**
 * 获得指定商品的销售排名
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  integer
 */
function get_goods_rank($goods_id){
	
	$CommonModel		=	new CommonModel();
	
    /* 统计时间段 */
    $period 			= 	intval($GLOBALS['_CFG']['top10_time']);
    if ($period == 1){ // 一年
        $ext 			= 	" AND o.add_time > '" . local_strtotime('-1 years') . "'";
    }
    elseif ($period == 2){ // 半年    
        $ext 			= 	" AND o.add_time > '" . local_strtotime('-6 months') . "'";
    }
    elseif ($period == 3){ // 三个月
        $ext 			= 	" AND o.add_time > '" . local_strtotime('-3 months') . "'";
    }
    elseif ($period == 4){ // 一个月
        $ext 			= 	" AND o.add_time > '" . local_strtotime('-1 months') . "'";
    }
    else{
        $ext 			= 	'';
    }

    /* 查询该商品销量 */
    $sql 				= 	'SELECT IFNULL(SUM(g.goods_number), 0) ' .
					        'FROM ' . 'ybr_order_info' . ' AS o, ' .
					        'ybr_order_goods' . ' AS g ' .
					        "WHERE o.order_id = g.order_id " .
					        "AND o.order_status = '" . OS_CONFIRMED . "' " .
					        "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
					        " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) .
					        " AND g.goods_id = '$goods_id'" . $ext;
    $sales_count 		= 	$CommonModel->getOne($sql);

    if ($sales_count > 0){
        /* 只有在商品销售量大于0时才去计算该商品的排行 */
        $sql 			= 	'SELECT DISTINCT SUM(goods_number) AS num ' .
                			'FROM ' . 'ybr_order_info' . ' AS o, ' .
                    		'ybr_order_goods' . ' AS g ' .
			                "WHERE o.order_id = g.order_id " .
			                "AND o.order_status = '" . OS_CONFIRMED . "' " .
			                "AND o.shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
			                " AND o.pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . $ext .
			                " GROUP BY g.goods_id HAVING num > $sales_count";
        //$res 			= 	$CommonModel->query($sql);
		$res			=	$CommonModel->getOne($sql);
		
		/* $res['num'] : 商品销售量 */
        if($res['num'] > 10){
        	$rank		=	0;
        }		
    }
    else{
        $rank = 0;
    }
    return $rank;
}



/**
 * 获得指定页面的动态内容
 *
 * @access  public
 * @param   string  $tmp    模板名称
 * @return  void
 */
function assign_dynamic($tmp){
	
	$GoodsAction	= 	A('Goods');  //参数为需要调用的模块名
	//$GoodsAction	= 	new GoodsAction();  //参数为需要调用的模块名
		
   	$sql 			= 	'SELECT id, number, type FROM ' . 'ybr_template' .
        				" WHERE filename = '$tmp' AND type > 0 AND remarks ='' AND theme='" . $GLOBALS['_CFG']['template'] . "'";
    $res 			= 	M()->query($sql);

   	foreach ($res AS $row){
        switch ($row['type']){
            case 1:
                /* 分类下的商品 */            	
                $GoodsAction->assign('goods_cat_' . $row['id'], assign_cat_goods($row['id'], $row['number']));
            break;
            case 2:
                /* 品牌的商品 */
                $brand_goods 		= 	assign_brand_goods($row['id'], $row['number']);

                $GoodsAction->assign('brand_goods_' . $row['id'], $brand_goods['goods']);
                $GoodsAction->assign('goods_brand_' . $row['id'], $brand_goods['brand']);
            break;
            case 3:
                /* 文章列表 */
                $cat_articles 		= 	assign_articles($row['id'], $row['number']);

                $GoodsAction->assign('articles_cat_' . $row['id'], $cat_articles['cat']);
                $GoodsAction->assign('articles_' . $row['id'], $cat_articles['arr']);
            break;
        }
    }
}


/**
 * 获得指定的品牌下的商品
 *
 * @access  public
 * @param   integer     $brand_id       品牌的ID
 * @param   integer     $num            数量
 * @param   integer     $cat_id         分类编号
 * @param   string      $order_rule     指定商品排序规则
 * @return  void
 */
function assign_brand_goods($brand_id, $num = 0, $cat_id = 0,$order_rule = ''){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			=  	'SELECT g.goods_id, g.goods_name, g.market_price, g.shop_price AS org_price, ' .
                		"IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
                		'g.promote_price, g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_thumb, g.goods_img ' .
			            'FROM ' . 'ybr_goods' . ' AS g ' .
			            "LEFT JOIN " . 'ybr_member_price' . " AS mp ".
			            " ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
			            " WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 AND g.brand_id = '$brand_id'";

    if ($cat_id > 0){
        $sql 		.= 	get_children($cat_id);
    }

    $order_rule 	= 	empty($order_rule) ? ' ORDER BY g.sort_order, g.goods_id DESC' : $order_rule;
    $sql 			.= 	$order_rule;
    if ($num > 0){
        $res 		= 	$CommonModel->query($sql);
    }
    else{
        $res 		= 	$CommonModel->query($sql);
    }

    $idx 			= 	0;
    $goods 			= 	array();
    
    foreach($res as $row){
    	if ($row['promote_price'] > 0){
            $promote_price 		= 	bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else{
            $promote_price 		= 	0;
        }

        $goods[$idx]['id']            = $row['goods_id'];
        $goods[$idx]['name']          = $row['goods_name'];
        $goods[$idx]['short_name']    = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $goods[$idx]['market_price']  = price_format($row['market_price']);
        $goods[$idx]['shop_price']    = price_format($row['shop_price']);
        $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : '';
        $goods[$idx]['brief']         = $row['goods_brief'];
        $goods[$idx]['thumb']         = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $goods[$idx]['goods_img']     = get_image_path($row['goods_id'], $row['goods_img']);
        $goods[$idx]['url']           = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);

        $idx++;
    }

    /* 分类信息 */
    $sql 			= 	'SELECT brand_name FROM ' . 'ybr_brand' . " WHERE brand_id = '$brand_id'";

    $brand['id']   	= 	$brand_id;
    $brand['name']	= 	$CommonModel->getOne($sql);
    //$brand['url']  	= 	build_uri('brand', array('bid' => $brand_id), $brand['name']);

    $brand_goods 	= 	array('brand' => $brand, 'goods' => $goods);

    return $brand_goods;
}

/**
 * 获得指定的规格的价格
 *
 * @access  public
 * @param   mix     $spec   规格ID的数组或者逗号分隔的字符串
 * @return  void
 */
function spec_price($spec){
	
	$CommonModel	=	new CommonModel();
	
    if (!empty($spec)){
        $where 	= 	db_create_in($spec, 'goods_attr_id');
        $sql 	= 	'SELECT SUM(attr_price) AS attr_price FROM ' . 'ybr_goods_attr' . " WHERE $where";
        $price 	= 	floatval($CommonModel->getOne($sql));
    }
    else{
        $price = 0;
    }
    return $price;
}

/**
 * 调用购物车信息
 *
 * @access  public
 * @return  string
 */
function insert_cart_info(){
	
	$CommonModel	=	new CommonModel();
	
    $sql 			= 	'SELECT SUM(goods_number) AS number, SUM(goods_price * goods_number) AS amount' .
			           	' FROM ' . 'ybr_cart' .
			           	" WHERE session_id = '" . SESS_ID . "' AND rec_type = '" . CART_GENERAL_GOODS . "'";
    $row 			= 	$CommonModel->getRow($sql);

    if ($row){
        $number 	= 	intval($row['number']);
        $amount 	= 	floatval($row['amount']);
    }
    else{
        $number 	= 	0;
        $amount 	= 	0;
    }
	
    return $row;
    //$str 			= 	sprintf($GLOBALS['_LANG']['cart_info'], $number, price_format($amount, false));	
    //return '<a href="'. U('flow/index') .'" title="' . $GLOBALS['_LANG']['view_cart'] . '">' . $str . '</a>';
}



/**
 * 添加商品到购物车
 *
 * @access  public
 * @param   integer $goods_id   商品编号
 * @param   integer $num        商品数量
 * @param   array   $spec       规格值对应的id数组
 * @param   integer $parent     基本件
 * @return  boolean
 */
function addto_cart($goods_id, $num = 1, $spec = array(), $parent = 0){
	
	$CommonModel		=	new CommonModel();
    $_parent_id 		= 	$parent;

    /* 取得商品信息 */
    $sql 				= 	"SELECT g.goods_name, g.goods_sn, g.is_on_sale, g.is_real, ".
			                "g.market_price, g.shop_price AS org_price, g.promote_price, g.promote_start_date, ".
			                "g.promote_end_date, g.goods_weight, g.integral, g.extension_code, ".
			                "g.goods_number, g.is_alone_sale, g.is_shipping,".
			                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price ".
			            	" FROM " . 'ybr_goods' . " AS g ".
			            	" LEFT JOIN " . 'ybr_member_price' . " AS mp ".
			                "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
			           		" WHERE g.goods_id = '$goods_id'" .
			            	" AND g.is_delete = 0";
    $goods 				= 	$CommonModel->getRow($sql);    
    
    if (empty($goods)){
        $GLOBALS['err']->add($GLOBALS['_LANG']['goods_not_exists'], ERR_NOT_EXISTS);
        return false;
    }
    
    /* 如果是作为配件添加到购物车的，需要先检查购物车里面是否已经有基本件 */
    if ($parent > 0){
        $sql 			= 	"SELECT COUNT(*) FROM " . 'ybr_cart' .
                			" WHERE goods_id='$parent' AND session_id='" . SESS_ID . "' AND extension_code <> 'package_buy'";        
        if ($CommonModel->getOne($sql) == 0){
            $GLOBALS['err']->add($GLOBALS['_LANG']['no_basic_goods'], ERR_NO_BASIC_GOODS);
            return false;
        }
    }
    /* 是否正在销售 */
    if ($goods['is_on_sale'] == 0){
        $GLOBALS['err']->add($GLOBALS['_LANG']['not_on_sale'], ERR_NOT_ON_SALE);
        return false;
    }

    /* 不是配件时检查是否允许单独销售 */
    if (empty($parent) && $goods['is_alone_sale'] == 0){
        $GLOBALS['err']->add($GLOBALS['_LANG']['cannt_alone_sale'], ERR_CANNT_ALONE_SALE);
        return false;
    }

    /* 如果商品有规格则取规格商品信息 配件除外 */
    $sql 				= 	"SELECT * FROM " .'ybr_products' . " WHERE goods_id = '$goods_id' LIMIT 0, 1";
    $prod 				= 	$CommonModel->getRow($sql);
	 
    if (is_spec($spec) && !empty($prod)){
        $product_info 	= 	get_products_info($goods_id, $spec);
    }
    if (empty($product_info)){
        $product_info 	= 	array('product_number' => '', 'product_id' => 0);
    }

    /* 检查：库存 */
    if ($GLOBALS['_CFG']['use_storage'] == 1){
        //检查：商品购买数量是否大于总库存
        if ($num > $goods['goods_number']){
            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $goods['goods_number']), ERR_OUT_OF_STOCK);
            return false;
        }

        //商品存在规格 是货品 检查该货品库存
        if (is_spec($spec) && !empty($prod)){
            if (!empty($spec)){
                /* 取规格的货品库存 */
                if ($num > $product_info['product_number']){
                   	$GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $product_info['product_number']), ERR_OUT_OF_STOCK);    
                    return false;
                }
            }
        }       
    }
    
    /* 计算商品的促销价格 */
    $spec_price             	= 	spec_price($spec);
    $goods_price            	= 	get_final_price($goods_id, $num, true, $spec);
    $goods['market_price'] 		+= 	$spec_price;
    $goods_attr             	= 	get_goods_attr_info($spec);
    $goods_attr_id          	= 	join(',', $spec);

    /* 初始化要插入购物车的基本件数据 */
    $parent = array(
        'user_id'       => $_SESSION['user_id'],
        'session_id'    => SESS_ID,
        'goods_id'      => $goods_id,
        'goods_sn'      => addslashes($goods['goods_sn']),
        'product_id'    => $product_info['product_id'],
        'goods_name'    => addslashes($goods['goods_name']),
        'market_price'  => $goods['market_price'],
        'goods_attr'    => addslashes($goods_attr),
        'goods_attr_id' => $goods_attr_id,
        'is_real'       => $goods['is_real'],
        'extension_code'=> $goods['extension_code'],
        'is_gift'       => 0,
        'is_shipping'   => $goods['is_shipping'],
        'rec_type'      => CART_GENERAL_GOODS
    );
	    
    /* 如果该配件在添加为基本件的配件时，所设置的“配件价格”比原价低，即此配件在价格上提供了优惠， */
    /* 则按照该配件的优惠价格卖，但是每一个基本件只能购买一个优惠价格的“该配件”，多买的“该配件”不享 */
    /* 受此优惠 */
    $basic_list 		= 	array();
    $sql 				= 	"SELECT parent_id, goods_price " .
				            "FROM " . 'ybr_group_goods' .
				            " WHERE goods_id = '$goods_id'" .
				            " AND goods_price < '$goods_price'" .
				            " AND parent_id = '$_parent_id'" .
				            " ORDER BY goods_price";
    $res 				= 	$CommonModel->query($sql);
    
    foreach($res as $row){
    	$basic_list[$row['parent_id']] = $row['goods_price'];
    }
    
    /* 取得购物车中该商品每个基本件的数量 */
    $basic_count_list 	= 	array();
    if ($basic_list){
        $sql 			= 	"SELECT goods_id, SUM(goods_number) AS count " .
			                "FROM " . 'ybr_cart' .
			                " WHERE session_id = '" . SESS_ID . "'" .
			                " AND parent_id = 0" .
			                " AND extension_code <> 'package_buy' " .
			                " AND goods_id " . db_create_in(array_keys($basic_list)) .
			                " GROUP BY goods_id";
        $res 			= 	$CommonModel->query($sql);
        
        foreach($res as $row){
        	$basic_count_list[$row['goods_id']] = $row['count'];
        }
    }

    /* 取得购物车中该商品每个基本件已有该商品配件数量，计算出每个基本件还能有几个该商品配件 */
    /* 一个基本件对应一个该商品配件 */
    if ($basic_count_list){
        $sql 			= 	"SELECT parent_id, SUM(goods_number) AS count " .
			                "FROM " . 'ybr_cart' .
			                " WHERE session_id = '" . SESS_ID . "'" .
			                " AND goods_id = '$goods_id'" .
			                " AND extension_code <> 'package_buy' " .
			                " AND parent_id " . db_create_in(array_keys($basic_count_list)) .
			                " GROUP BY parent_id";
        $res 			= 	$CommonModel->query($sql);
        
        foreach($res as $row){
        	$basic_count_list[$row['parent_id']] -= $row['count'];
        }
        
    }
	
    
    /* 循环插入配件 如果是配件则用其添加数量依次为购物车中所有属于其的基本件添加足够数量的该配件 */
    foreach ($basic_list as $parent_id => $fitting_price){    	
        /* 如果已全部插入，退出 */
        if ($num <= 0){
            break;
        }

        /* 如果该基本件不再购物车中，执行下一个 */
        if (!isset($basic_count_list[$parent_id])){
            continue;
        }

        /* 如果该基本件的配件数量已满，执行下一个基本件 */
        if ($basic_count_list[$parent_id] <= 0){
            continue;
        }

        /* 作为该基本件的配件插入 */
        $parent['goods_price']  	= 	max($fitting_price, 0) + $spec_price; //允许该配件优惠价格为0
        $parent['goods_number'] 	= 	min($num, $basic_count_list[$parent_id]);
        $parent['parent_id']    	= 	$parent_id;

        /* 添加 */
        $CommonModel->autoExecute('cart', $parent, 'INSERT');

        /* 改变数量 */
        $num 						-= 	$parent['goods_number'];
    }
    
    /* 如果数量不为0，作为基本件插入 */
    if ($num > 0){
        /* 检查该商品是否已经存在在购物车中 */
        $sql 						= 	"SELECT goods_number FROM " .'ybr_cart' .
						                " WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ".
						                " AND parent_id = '{$_parent_id}' AND goods_attr = '" .get_goods_attr_info($spec). "' " .
						                " AND extension_code <> 'package_buy' " .
						                " AND rec_type = 'CART_GENERAL_GOODS'";

        $row 						= 	$CommonModel->getRow($sql);
    
        if($row){ //如果购物车已经有此物品，则更新
            $num 					+= 	$row['goods_number'];
            
            if(is_spec($spec) && !empty($prod) ){
             $goods_storage			=	$product_info['product_number'];
            }
            else{
                $goods_storage		=	$goods['goods_number'];
            }
            if ($GLOBALS['_CFG']['use_storage'] == 0 || $num <= $goods_storage){
            	
                $goods_price 		= 	get_final_price($goods_id, $num, true, $spec);
                $sql 				= 	"UPDATE " . 'ybr_cart' . " SET goods_number = '$num'" .
				                       	" , goods_price = '$goods_price'".
				                       	" WHERE session_id = '" .SESS_ID. "' AND goods_id = '$goods_id' ".
				                       	" AND parent_id = '{$_parent_id}' AND goods_attr = '" .get_goods_attr_info($spec). "' " .
				                       	" AND extension_code <> 'package_buy' " .
				                       	"AND rec_type = '" . CART_GENERAL_GOODS . "'";
                
                $CommonModel->query($sql);
            }
            else{
	            $GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['shortage'], $num), ERR_OUT_OF_STOCK);
                return false;
            }
        }
        else{//购物车没有此物品，则插入    	
            $goods_price 			= 	get_final_price($goods_id, $num, true, $spec);
            $parent['goods_price']  = 	max($goods_price, 0);
            $parent['goods_number'] = 	$num;
            $parent['parent_id']    = 	$_parent_id;
            
            $CommonModel->autoExecute('cart', $parent, 'INSERT');
        }
    }    
    /* 把赠品删除 */
    $sql 							= 	"DELETE FROM " . 'ybr_cart' . " WHERE session_id = '" . SESS_ID . "' AND is_gift <> 0";
   	$CommonModel->query($sql);
    return true;
}


/**
 * 取指定规格的货品信息
 *
 * @access      public
 * @param       string      $goods_id
 * @param       array       $spec_goods_attr_id
 * @return      array
 */
function get_products_info($goods_id, $spec_goods_attr_id){
	$CommonModel			=	new CommonModel();
    $return_array 		= 	array();

    if (empty($spec_goods_attr_id) || !is_array($spec_goods_attr_id) || empty($goods_id)){
        return $return_array;
    }

    $goods_attr_array 	= 	sort_goods_attr_id_array($spec_goods_attr_id);

    if(isset($goods_attr_array['sort'])){
        $goods_attr 	= 	implode('|', $goods_attr_array['sort']);

        $sql 			= 	"SELECT * FROM " . 'ybr_products' . " WHERE goods_id = '$goods_id' AND goods_attr = '$goods_attr' LIMIT 0, 1";
        $return_array 	= 	$CommonModel->getRow($sql);
    }
    return $return_array;
}


/**
 * 将 goods_attr_id 的序列按照 attr_id 重新排序
 *
 * 注意：非规格属性的id会被排除
 *
 * @access      public
 * @param       array       $goods_attr_id_array        一维数组
 * @param       string      $sort                       序号：asc|desc，默认为：asc
 *
 * @return      string
 */
function sort_goods_attr_id_array($goods_attr_id_array, $sort = 'asc'){
    if (empty($goods_attr_id_array)){
        return $goods_attr_id_array;
    }

    //重新排序
    $sql 		= 	"SELECT a.attr_type, v.attr_value, v.goods_attr_id
            		FROM " .'ybr_attribute'. " AS a
            		LEFT JOIN " .'ybr_goods_attr'. " AS v
                	ON v.attr_id = a.attr_id
                	AND a.attr_type = 1
            		WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . "
            		ORDER BY a.attr_id $sort";
    $row 		= 	M()->query($sql);

    $return_arr = 	array();
    foreach ($row as $value){
        $return_arr['sort'][]   						= 	$value['goods_attr_id'];
        $return_arr['row'][$value['goods_attr_id']]    	=	 $value;
    }
    return $return_arr;
}


/**
 * 获得指定的商品属性
 *
 * @access      public
 * @param       array       $arr        规格、属性ID数组
 * @param       type        $type       设置返回结果类型：pice，显示价格，默认；no，不显示价格
 *
 * @return      string
 */
function get_goods_attr_info($arr, $type = 'pice'){
	
	$CommonModel	=	new CommonModel();
    $attr   		= 	'';

    if (!empty($arr)){
        $fmt 		= 	"%s:%s[%s] \n";

        $sql 		= 	"SELECT a.attr_name, ga.attr_value, ga.attr_price ".
		                "FROM " . 'ybr_goods_attr' . " AS ga, ".
		                'ybr_attribute' ." AS a ".
                		"WHERE " .db_create_in($arr, 'ga.goods_attr_id')." AND a.attr_id = ga.attr_id";
        $res 		= 	$CommonModel->query($sql);
		
        foreach($res as $row){
        	$attr_price = round(floatval($row['attr_price']), 2);
            $attr .= sprintf($fmt, $row['attr_name'], $row['attr_value'], $attr_price);
        }
        $attr = str_replace('[0]', '', $attr);
    }
    return $attr;
}


/**
 * 获取套餐的商品,并于配件进行分配
 * 
 */
function check_to_package($goods_id, $fittings){
	if(empty($fittings)) return array();
	
	foreach($fittings as $k=>$row){
		$fittings[$k]['number']	=	3;
	}
	return $fittings;
}


/**
 * 计算套餐的价值
 * 
 */
function calculate_package_price($goods,$fittings){
	
	$price_list	=	array();
	
	if(empty($fittings)){// 只有主商品的时候
		$price_list['original_price']		=	$goods['market_price'] + $price;		// 套装原价	
		$price_list['package_price']		=	$goods['market_price'] + $price * 0.95; // 配件打95折,套装价
		$price_list['fittings_total_price']	=	$price * 0.95; // 配件打95折,套装价
		$price_list['saved_price']			=	$price_list['original_price'] - $price_list['package_price']; // 配件打95折,套装价
	}
	else{
		$price = 0;
		foreach($fittings as $row){
			$price += $row['fittings_price'] * $row['number'];
		}	
		
		$price_list['original_price']		=	ceil( $goods['market_price'] + $price );		// 套装原价	
		$price_list['package_price']		=	ceil( $goods['market_price'] + $price * 0.95 ); // 配件打95折,套装价
		$price_list['fittings_total_price']	=	ceil( $price ); // 配件打95折,套装价
		$price_list['saved_price']			=	ceil( $price_list['original_price'] - $price_list['package_price'] ); // 配件打95折,套装价
	}
	return $price_list;
}









